/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.mzk.oai.metadataRepository.cli;

import cz.mzk.kramerius.commons.Dom4jUtils;
import cz.mzk.oai.metadataRepository.repository.Identifier;
import cz.mzk.oai.metadataRepository.repository.Repository;
import cz.mzk.oai.metadataRepository.repository.collections.MetadataCollection;
import cz.mzk.oai.metadataRepository.repository.collections.NoCollectionFoundException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Document;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class PrintCollectionsOfItemsAction extends Action {

    private final File itemsIds;

    public PrintCollectionsOfItemsAction(Repository repository, String itemsIdFile) {
        super(repository);
        itemsIds = new File(itemsIdFile);
    }

    @Override
    public void run() throws Exception {
        if (!itemsIds.isFile() || !itemsIds.canRead()) {
            throw new Exception("'" + itemsIds.getAbsolutePath() + " is not file or cannot be read");
        }
        List<Identifier> idList = readIdentifiers(itemsIds);
        CollectionsItemsMapping mapping = new CollectionsItemsMapping();
        fillMapping(idList, mapping);
        printItemsInCollections(mapping);
    }

    private List<Identifier> readIdentifiers(File idsFile) throws Exception {
        List<Identifier> result = new ArrayList<Identifier>();
        LineNumberReader reader = new LineNumberReader(new BufferedReader(new FileReader(idsFile)));
        while (reader.ready()) {
            String line = reader.readLine();
            try {
                Identifier id = Identifier.parseNotEncodedString(line);
                result.add(id);
            } catch (RuntimeException e) {
                System.err.println("cannot parse id '" + line + "': " + e.getMessage());
            }
        }
        return result;
    }

    private void fillMapping(List<Identifier> idList, CollectionsItemsMapping mapping) {
        for (Identifier id : idList) {
            MetadataCollection collection = null;
            try {
                collection = repository.selectCollection(id);
            } catch (NoCollectionFoundException ex) {
                Logger.getLogger(PrintCollectionsOfItemsAction.class.getName()).log(Level.SEVERE, id.toString(), ex);
            }
            mapping.addItem(id, collection.getName());
        }
    }

    private void printItemsInCollections(CollectionsItemsMapping mapping) {
        Document printDoc = mapping.asXml();
        Dom4jUtils.writeDocument(printDoc, System.out, Dom4jUtils.PrintType.PRETTY);
    }
}
